package com.rongji.dfish.hello.controller;

import com.rongji.dfish.base.util.Utils;
import com.rongji.dfish.framework.mvc.controller.BaseActionController;
import com.rongji.dfish.framework.mvc.response.JsonResponse;
import com.rongji.dfish.hello.constant.DemoConstants;
import com.rongji.dfish.hello.entity.SysOrg;
import com.rongji.dfish.hello.service.OrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/org")
@Controller
public class OrgController extends BaseActionController {

    @Autowired
    private OrgService orgService;

    @RequestMapping("/save")
    @ResponseBody
    public Object save(HttpServletRequest request) throws Exception {

        SysOrg org = new SysOrg();
        bind(request, org);

        if (Utils.isEmpty(org.getOrgStatus())) {
            org.setOrgStatus(DemoConstants.STATUS_ENABLE);
        }

        if (Utils.isEmpty(org.getOrgId())) {
            org.setOrgId(orgService.getNewId());
            orgService.save(org);
        } else {
            orgService.update(org);
        }

        return new JsonResponse(org);
    }

    @RequestMapping("/children")
    @ResponseBody
    public Object children(HttpServletRequest request) {
        String parent = request.getParameter("parent");

        List<SysOrg> orgList = orgService.listChildren(parent);
        return new JsonResponse<>(orgList);
    }

    @RequestMapping("/get")
    @ResponseBody
    public Object get(HttpServletRequest request) {
        String orgId = request.getParameter("orgId");
        SysOrg org;
        if (Utils.isEmpty(orgId)) {
            org = new SysOrg();
            // FIXME
            String orgParent = request.getParameter("orgParent");
            orgParent = Utils.isEmpty(orgParent) ? DemoConstants.ID_ROOT : orgParent;
            org.setOrgParent(orgParent);
        } else {
            org = orgService.get(orgId);
        }
        return new JsonResponse<>(org);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete (HttpServletRequest request) {
        String orgId = request.getParameter("orgId");
        orgService.updateStatus(orgId, DemoConstants.STATUS_DELETE);
        return new JsonResponse<>(orgId);
    }


}
